// SSH功能相关DOM元素
const $sshConnectForm = document.querySelector('#ssh-connect-form');
const $sshHost = document.querySelector('#ssh-host');
const $sshPort = document.querySelector('#ssh-port');
const $sshUsername = document.querySelector('#ssh-username');
const $sshPassword = document.querySelector('#ssh-password');
const $sshConnectBtn = document.querySelector('#ssh-connect-btn');
const $sshDisconnectBtn = document.querySelector('#ssh-disconnect-btn');
const $terminalContainer = document.querySelector('#terminal-container');
const $sshConnectionStatus = document.querySelector('#ssh-connection-status');
const $terminalStatus = document.querySelector('#terminal-status');
const $sshCurrentHost = document.querySelector('#ssh-current-host');
const $sshCurrentUser = document.querySelector('#ssh-current-user');
// SSH 连接配置侧边面板相关元素
const $sshConfigPanel = document.querySelector('#ssh-config-panel');
const $sshConfigToggle = document.querySelector('#ssh-config-toggle');
const $sshConfigClose = document.querySelector('#ssh-config-close');
// 多服务器列表相关元素
const $sshServerList = document.querySelector('#ssh-server-list');
const $sshAddServerBtn = document.querySelector('#ssh-add-server-btn');
// 新增服务器模态框相关元素
const $sshAddServerModal = document.querySelector('#sshAddServerModal');
const $sshAddServerSaveBtn = document.querySelector('#ssh-add-server-save');
const $sshAddAlias = document.querySelector('#ssh-add-alias');
const $sshAddHost = document.querySelector('#ssh-add-host');
const $sshAddPort = document.querySelector('#ssh-add-port');
const $sshAddUsername = document.querySelector('#ssh-add-username');
const $sshAddPassword = document.querySelector('#ssh-add-password');
let sshServers = [];

// SSH WebSocket连接和xterm.js相关变量
let sshSocket = null;
let isConnected = false;
let currentSshHost = '';
let currentSshUser = '';
let terminal = null;
let fitAddon = null;
let webLinksAddon = null;

// 初始化SSH功能
function initSSH() {
  console.log('初始化SSH功能 - 使用xterm.js');
  
  // 初始化xterm.js终端
  initTerminal();
  
  // 设置连接表单提交事件
  $sshConnectForm.addEventListener('submit', (e) => {
    e.preventDefault();
    connectSSH();
  });
  
  // 设置断开连接按钮点击事件
  $sshDisconnectBtn.addEventListener('click', disconnectSSH);

  // 绑定侧边面板展开/隐藏事件
  if ($sshConfigToggle && $sshConfigPanel) {
    $sshConfigToggle.addEventListener('click', () => {
      $sshConfigPanel.classList.add('open');
    });
  }
  if ($sshConfigClose && $sshConfigPanel) {
    $sshConfigClose.addEventListener('click', () => {
      $sshConfigPanel.classList.remove('open');
    });
  }

  // 加载服务器列表 & 绑定新增事件（使用Bootstrap模态框）
  // 仅使用 data-bs-toggle="modal" 打开弹窗，避免重复创建实例导致遮罩不消失
  // 在弹窗显示时重置表单
  if ($sshAddServerModal) {
    $sshAddServerModal.addEventListener('show.bs.modal', () => {
      if ($sshAddAlias) $sshAddAlias.value = '';
      if ($sshAddHost) $sshAddHost.value = '';
      if ($sshAddPort) $sshAddPort.value = '22';
      if ($sshAddUsername) $sshAddUsername.value = '';
      if ($sshAddPassword) $sshAddPassword.value = '';
    });
  }
  if ($sshAddServerSaveBtn) {
    $sshAddServerSaveBtn.addEventListener('click', saveNewServerFromModal);
  }
  loadSshServers();
  
  console.log('SSH功能初始化完成');
}

// 加载服务器列表
async function loadSshServers() {
  try {
    const resp = await fetch('/api/ssh/servers');
    if (!resp.ok) throw new Error('加载服务器列表失败');
    sshServers = await resp.json();
    renderSshServerList();
  } catch (e) {
    console.error('加载服务器列表失败:', e);
    if ($sshServerList) {
      $sshServerList.innerHTML = '<div class="text-center text-danger p-2">加载服务器列表失败</div>';
    }
  }
}

// 渲染服务器列表
function renderSshServerList() {
  if (!$sshServerList) return;
  $sshServerList.innerHTML = '';
  if (!sshServers || sshServers.length === 0) {
    $sshServerList.innerHTML = '<div class="text-center text-muted p-2">暂无服务器，请点击“新增”添加</div>';
    return;
  }
  sshServers.forEach(s => {
    const item = document.createElement('div');
    item.className = 'list-group-item d-flex justify-content-between align-items-center';
    item.innerHTML = `
      <div class="flex-grow-1 cursor-pointer">
        <div class="fw-semibold">${escapeHtml(s.alias || s.hostname)}</div>
        <div class="text-muted small">${escapeHtml(s.username)}@${escapeHtml(s.hostname)}:${s.port}</div>
      </div>
      <div class="server-actions btn-group btn-group-sm ms-2" role="group" aria-label="Server Actions">
        <button class="server-edit-btn btn btn-outline-primary btn-xxs" title="编辑">编辑</button>
        <button class="server-delete-btn btn btn-outline-danger btn-xxs" title="删除">删除</button>
      </div>
    `;
    const infoDiv = item.querySelector('.flex-grow-1');
    infoDiv.addEventListener('click', () => selectServerAndConnect(s));
    const editBtn = item.querySelector('.server-edit-btn');
    editBtn.addEventListener('click', (ev) => { ev.stopPropagation(); editServerPrompt(s); });
    const deleteBtn = item.querySelector('.server-delete-btn');
    deleteBtn.addEventListener('click', (ev) => { ev.stopPropagation(); deleteServerConfirm(s); });
    $sshServerList.appendChild(item);
  });
}

// 选择服务器并连接
async function selectServerAndConnect(s) {
  $sshHost.value = s.hostname || '';
  $sshPort.value = s.port || 22;
  $sshUsername.value = s.username || '';
  $sshPassword.value = s.password || '';
  if (!$sshPassword.value) {
    const pwd = window.prompt('请输入密码（不会保存到列表中，或在编辑时保存）', '');
    if (pwd !== null) { $sshPassword.value = pwd; }
  }
  if (isConnected) { try { disconnectSSH(); } catch (_) {} }
  connectSSH();
}

  // 新增服务器（Bootstrap模态框版本）
  async function saveNewServerFromModal() {
    try {
    const alias = ($sshAddAlias && $sshAddAlias.value || '').trim();
    const hostname = ($sshAddHost && $sshAddHost.value || '').trim();
    const port = parseInt(($sshAddPort && $sshAddPort.value || '22').trim(), 10) || 22;
    const username = ($sshAddUsername && $sshAddUsername.value || '').trim();
    const password = ($sshAddPassword && $sshAddPassword.value || '').trim();

    if (!alias || !hostname || !username) {
      alert('别名、主机地址、用户名为必填项');
      return;
    }

    const resp = await fetch('/api/ssh/servers', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ alias, hostname, port, username, password })
    });
    if (!resp.ok) throw new Error('新增失败');

    // 关闭模态框：使用已存在的实例，避免重复实例残留遮罩
    if (window.bootstrap && $sshAddServerModal) {
      try {
        const modal = bootstrap.Modal.getInstance($sshAddServerModal);
        if (modal) { modal.hide(); }
      } catch (_) {}
    }

    await loadSshServers();
  } catch (e) {
    console.error('新增服务器失败:', e);
    alert('新增服务器失败');
  }
}

// 编辑服务器
async function editServerPrompt(s) {
  const alias = window.prompt('别名', s.alias || ''); if (alias === null) return;
  const hostname = window.prompt('主机地址', s.hostname || ''); if (hostname === null) return;
  const portStr = window.prompt('端口', String(s.port || 22)); if (portStr === null) return; const port = parseInt(portStr) || 22;
  const username = window.prompt('用户名', s.username || ''); if (username === null) return;
  const password = window.prompt('密码（可留空）', s.password || ''); if (password === null) return;
  try {
    const resp = await fetch(`/api/ssh/servers/${s.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ alias, hostname, port, username, password })
    });
    if (!resp.ok) throw new Error('更新失败');
    await loadSshServers();
  } catch (e) {
    console.error('更新服务器失败:', e);
    alert('更新服务器失败');
  }
}

// 删除服务器
async function deleteServerConfirm(s) {
  if (!confirm(`确认删除服务器：${s.alias || s.hostname}?`)) return;
  try {
    const resp = await fetch(`/api/ssh/servers/${s.id}`, { method: 'DELETE' });
    if (!resp.ok) throw new Error('删除失败');
    await loadSshServers();
  } catch (e) {
    console.error('删除服务器失败:', e);
    alert('删除服务器失败');
  }
}

// 简单HTML转义（避免XSS）
function escapeHtml(str) {
  if (!str) return '';
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

// 初始化xterm.js终端
function initTerminal() {
  // 创建终端实例
  terminal = new Terminal({
    cursorBlink: true,
    cursorStyle: 'block',
    fontSize: 14,
    fontFamily: 'Consolas, "Courier New", monospace',
    theme: {
      background: '#000000',
      foreground: '#ffffff',
      cursor: '#ffffff',
      selection: '#ffffff40',
      black: '#000000',
      red: '#cd0000',
      green: '#00cd00',
      yellow: '#cdcd00',
      blue: '#0000ee',
      magenta: '#cd00cd',
      cyan: '#00cdcd',
      white: '#e5e5e5',
      brightBlack: '#7f7f7f',
      brightRed: '#ff0000',
      brightGreen: '#00ff00',
      brightYellow: '#ffff00',
      brightBlue: '#5c5cff',
      brightMagenta: '#ff00ff',
      brightCyan: '#00ffff',
      brightWhite: '#ffffff'
    },
    allowTransparency: false,
    convertEol: true,
    scrollback: 1000,
    tabStopWidth: 4
  });

  // 创建并加载插件
  fitAddon = new FitAddon.FitAddon();
  webLinksAddon = new WebLinksAddon.WebLinksAddon();
  
  terminal.loadAddon(fitAddon);
  terminal.loadAddon(webLinksAddon);

  // 将终端挂载到DOM
  terminal.open($terminalContainer);
  
  // 调整终端大小以适应容器
  fitAddon.fit();
  // 初始聚焦终端，确保能接收键盘输入
  try {
    terminal.focus();
  } catch (_) {}
  // 点击容器时强制聚焦终端
  $terminalContainer.addEventListener('click', () => {
    try { terminal.focus(); } catch (_) {}
  });
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (fitAddon) {
      fitAddon.fit();
    }
  });
  let cmd = '';
  // 监听终端输入
  terminal.onData((data) => {
    console.log('收到终端输入:', data);
    // 避免重复发送Enter：自定义键盘处理已单独发送CR
    if (data === '\r' || data === '\n') {
      return;
    }
    if (sshSocket && sshSocket.readyState === WebSocket.OPEN) {
      const inputData = {
        type: 'input',
        data: data
      };
      console.log('发送输入数据:', data);
      try {
        sshSocket.send(JSON.stringify(inputData));
        console.log('数据发送成功');
      } catch (error) {
        console.error('发送数据失败:', error);
        terminal.write('\r\n\x1b[31m发送数据失败: ' + error.message + '\x1b[0m\r\n');
      }
    }
  });
  
  // 显示欢迎信息
  terminal.write('\x1b[36m=== SSH 终端 ===\x1b[0m\r\n');
  terminal.write('\x1b[33m请在左侧配置并连接到SSH服务器\x1b[0m\r\n\r\n');
  
  console.log('xterm.js终端初始化完成');

  // 拦截Enter键：显式发送CR并阻止可能的表单提交
  try {
    terminal.attachCustomKeyEventHandler((ev) => {
      if (ev && ev.key === 'Enter') {
        console.log('拦截Enter键，发送LF到后端');
        try { ev.preventDefault(); ev.stopPropagation(); } catch (_) {}
        if (sshSocket && sshSocket.readyState === WebSocket.OPEN) {
          try {
            sshSocket.send(JSON.stringify({ type: 'input', data: '\n' }));
            console.log('LF发送成功');
          } catch (error) {
            console.error('发送LF失败:', error);
            terminal.write('\r\n\x1b[31m发送LF失败: ' + error.message + '\x1b[0m\r\n');
          }
        }
        return false; // 阻止xterm默认处理，避免触发表单提交
      }
      return true;
    });
  } catch (_) {}
}

// 连接SSH服务器
function connectSSH() {
  // 防止重复连接
  if (isConnected) {
    return;
  }
  
  const host = $sshHost.value.trim();
  const port = $sshPort.value.trim();
  const username = $sshUsername.value.trim();
  const password = $sshPassword.value.trim();
  
  // 验证表单
  if (!host || !port || !username) {
    terminal.write('\x1b[31m错误: 请填写所有必填字段\x1b[0m\r\n');
    return;
  }
  
  // 记录当前连接信息
  currentSshHost = host;
  currentSshUser = username;
  
  // 清空终端
  terminal.clear();
  
  // 更新UI状态
  updateConnectionStatus(true, '连接中...');
  disableConnectForm(true);
  
  // 显示连接信息
  terminal.write('\x1b[36m=== 正在连接SSH服务器 ===\x1b[0m\r\n');
  terminal.write(`\x1b[33m目标: ${username}@${host}:${port}\x1b[0m\r\n`);
  
  // 构建WebSocket URL
  const { location } = window;
  const proto = location.protocol.startsWith('https') ? 'wss' : 'ws';
  const wsUri = `${proto}://${location.host}/ws/ssh-pty`;
  
  // 创建WebSocket连接
  sshSocket = new WebSocket(wsUri);
  
  // WebSocket事件处理
  sshSocket.onopen = () => {
    terminal.write(`\x1b[32m已连接到WebSocket服务器: ${wsUri}\x1b[0m\r\n`);
    
    // 发送SSH连接请求
    // 计算当前终端列/行（若不可用则回退80x24）
    try { if (fitAddon) { fitAddon.fit(); } } catch (_) {}
    const cols = (terminal && typeof terminal.cols === 'number') ? terminal.cols : 80;
    const rows = (terminal && typeof terminal.rows === 'number') ? terminal.rows : 24;
    const connectRequest = {
      type: 'connect',
      credentials: {
        hostname: host,
        port: parseInt(port),
        username,
        password
      },
      col_width: cols,
      row_height: rows
    };
    sshSocket.send(JSON.stringify(connectRequest));
    // 兼容后端未发送connected事件的情况，先标记为已连接并聚焦
    isConnected = true;
    updateConnectionStatus(true, '已连接');
    try { terminal.focus(); } catch (_) {}
  };
  
  sshSocket.onmessage = (event) => {
    handleSSHMessage(event.data);
  };
  
  sshSocket.onclose = () => {
    terminal.write('\r\n\x1b[33m与WebSocket服务器的连接已断开\x1b[0m\r\n');
    updateConnectionStatus(false);
    disableConnectForm(false);
    sshSocket = null;
    isConnected = false;
  };
  
  sshSocket.onerror = (error) => {
    console.error('WebSocket错误详情:', error);
    terminal.write(`\r\n\x1b[31mWebSocket连接错误: ${error.type || 'Unknown error'}\x1b[0m\r\n`);
    if (error.code) {
      terminal.write(`\x1b[31m错误代码: ${error.code}\x1b[0m\r\n`);
    }
    if (error.reason) {
      terminal.write(`\x1b[31m错误原因: ${error.reason}\x1b[0m\r\n`);
    }
    updateConnectionStatus(false);
    disableConnectForm(false);
    sshSocket = null;
    isConnected = false;
  };
}

// 断开SSH连接
function disconnectSSH() {
  if (!isConnected || !sshSocket) {
    return;
  }
  
  // 发送断开连接请求
  const disconnectRequest = {
    type: 'disconnect'
  };
  sshSocket.send(JSON.stringify(disconnectRequest));
  
  // 关闭WebSocket连接
  sshSocket.close();
  
  updateConnectionStatus(false);
  disableConnectForm(false);
  isConnected = false;
  
  terminal.write('\r\n\x1b[33m=== SSH连接已断开 ===\x1b[0m\r\n');
}

// 处理SSH消息
function handleSSHMessage(message) {
  try {
    // 尝试解析JSON消息
    const data = JSON.parse(message);
    
    switch (data.type) {
      case 'connected':
        // SSH连接成功
        isConnected = true;
        updateConnectionStatus(true, '已连接');
        terminal.write('\r\n\x1b[32m=== SSH连接成功 ===\x1b[0m\r\n');
        terminal.write(`\x1b[36m已连接到: ${currentSshUser}@${currentSshHost}\x1b[0m\r\n\r\n`);
        
        // 确保终端获得焦点
        terminal.focus();
        console.log('SSH连接成功，终端已获得焦点');
        break;
        
      case 'disconnected':
        // SSH断开连接
        isConnected = false;
        updateConnectionStatus(false);
        terminal.write('\r\n\x1b[33m=== SSH连接已断开 ===\x1b[0m\r\n');
        break;
        
      case 'output':
        // SSH命令输出 - 直接写入终端
        const output = data.data || data.content;
        if (output) {
          terminal.write(output);
        }
        break;
        
      case 'error':
        // SSH错误消息
        terminal.write(`\r\n\x1b[31mSSH错误: ${data.message}\x1b[0m\r\n`);
        break;
        
      default:
        // 未知消息类型
        terminal.write(`\r\n\x1b[31m未知消息类型: ${data.type}\x1b[0m\r\n`);
    }
  } catch (e) {
    // 非JSON格式消息直接显示
    terminal.write(message);
  }
}

// 更新连接状态UI
function updateConnectionStatus(connected, statusText = '') {
  const statusBadge = $sshConnectionStatus.querySelector('span.badge');
  const terminalStatusBadge = $terminalStatus;
  
  if (connected) {
    statusBadge.className = 'badge bg-success text-white';
    statusBadge.textContent = statusText || '已连接';
    
    terminalStatusBadge.className = 'badge bg-success text-white me-2';
    terminalStatusBadge.textContent = statusText || '已连接';
    
    // 显示连接信息
    $sshCurrentHost.style.display = 'block';
    $sshCurrentHost.querySelector('span').textContent = currentSshHost;
    
    $sshCurrentUser.style.display = 'block';
    $sshCurrentUser.querySelector('span').textContent = currentSshUser;
    
    // 启用断开连接按钮
    $sshDisconnectBtn.disabled = false;
  } else {
    statusBadge.className = 'badge bg-danger text-white';
    statusBadge.textContent = '未连接';
    
    terminalStatusBadge.className = 'badge bg-danger text-white me-2';
    terminalStatusBadge.textContent = '未连接';
    
    // 隐藏连接信息
    $sshCurrentHost.style.display = 'none';
    $sshCurrentUser.style.display = 'none';
    
    // 禁用断开连接按钮
    $sshDisconnectBtn.disabled = true;
  }
}

// 启用/禁用连接表单
function disableConnectForm(disabled) {
  $sshHost.disabled = disabled;
  $sshPort.disabled = disabled;
  $sshUsername.disabled = disabled;
  $sshPassword.disabled = disabled;
  $sshConnectBtn.disabled = disabled;
}

// 调整终端大小
function resizeTerminal() {
  if (fitAddon) {
    fitAddon.fit();
  }
}

// 导出初始化函数
window.initSSH = initSSH;
window.resizeTerminal = resizeTerminal;
